# MQTT客户端

import paho.mqtt.client as mqtt
from tortoise.expressions import F


class MQTTClient:
    def __init__(self):
        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message

    async def on_connect(self, client, userdata, flags, rc):
        client.subscribe("devices/+/status")
        client.subscribe("devices/+/update/progress")

    async def on_message(self, client, userdata, msg):
        topic_parts = msg.topic.split('/')
        device_id = topic_parts[1]

        if topic_parts[-1] == "status":
            await Device.filter(device_id=device_id).update(
                status=msg.payload.decode(),
                last_seen=timezone.now()
            )
        elif topic_parts[-1] == "progress":
            await FirmwareUpdate.filter(
                device__device_id=device_id
            ).update(progress=msg.payload.decode())

    def start(self):
        self.client.connect("mqtt_broker", 1883, 60)
        self.client.loop_start()


mqtt_client = MQTTClient()